package com.sctvcloud.dongqu.ui.activities;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.base.BaseActivity;
import com.sctvcloud.dongqu.beans.FCityItem;
import com.sctvcloud.dongqu.beans.FCityState;
import com.sctvcloud.dongqu.beans.GovItemBean;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.AbsNetCallBack;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.utils.ListTypeUtils;
import com.sctvcloud.dongqu.utils.UserManager;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MoreServiceActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {

    @BindView(R.id.title_top_back)
    ImageView titleTopBack;
    @BindView(R.id.title_top_title)
    CustomFontTextView titleTopTitle;
    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.can_content_view)
    RecyclerView canContentView;
    @BindView(R.id.common_refresh)
    CanRefreshLayout commonRefresh;
    private FCityItem cityItem;
    private String id;
    private GovItemBean currentBean;
    private Myadapter myadapter;
    private GridLayoutManager gridLayoutManager;
    private NormalServiceAdapter adapter;
    private String serviceUrlTemp;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more_service);
        ButterKnife.bind(this);
        titleTopTitle.setText("网办生活");
        commonRefresh.setRefreshEnabled(true);
        commonRefresh.setOnRefreshListener(this);
        commonRefresh.setOnLoadMoreListener(this);
        commonRefresh.setLoadMoreEnabled(false);
        serviceUrlTemp=getIntent().getStringExtra(BaseActivity.EX_URL);
        currentBean = (GovItemBean) getIntent().getSerializableExtra(BaseActivity.EX_NEWS_ITEM);
       if(cityItem==null){
            if(serviceUrlTemp!=null){
                getCityStateList();
            }
        }
       setServiceItemClick(new OnServiceItemClick() {
           @Override
           public void OnServiceItemClick(NewsItem item) {
               toH5(item);
           }
       });
    }


    @OnClick(R.id.title_top_back)
    public void onViewClicked(View view) {
          if(view==titleTopBack){
              finish();
          }
    }

    @Override
    public void onRefresh() {
        if(commonRefresh.isRefreshing()){
            commonRefresh.refreshComplete();
            return;
        }

//        if(currentBean!=null){
//            getServiceDynamicList(currentBean);
//        }
//        if(cityItem==null){
//            if(serviceUrlTemp!=null){
//                getCityStateList();
//            }
//        }
        if(currentBean!=null){
            getServiceDynamicList(currentBean);
        }
    }

    private void toH5(NewsItem item){
        if(item.getNewsUrl().equalsIgnoreCase("http://file.scwy.tv/logo/page.html")) {
            if (UserManager.isLoginS()) {
                Intent intent = new Intent(this, H5NormalActivity.class);
                intent.putExtra(EX_TITLE, item.getDataTitle());
                intent.putExtra(EX_HTML, item.getNewsUrl());
                startActivity(intent);
            } else {
                toLogin();
            }
        }else{
            Intent intent = new Intent(this, H5NormalActivity.class);
            intent.putExtra(EX_TITLE, item.getDataTitle());
            intent.putExtra(EX_HTML, item.getNewsUrl());
            startActivity(intent);
        }
    }

    @Override
    public void onLoadMore() {

    }

    private class Myadapter extends BaseAdapter{
        private List<GovItemBean> beans;

        public Myadapter(List<GovItemBean> beans) {
            this.beans = beans;
        }
       public void clearData(){
            this.beans.clear();
        }
        @Override
        public int getCount() {
            return beans.size();
        }

        @Override
        public Object getItem(int position) {
            return beans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder=null;
            GovItemBean bean=beans.get(position);
            if(convertView==null){
                convertView= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_more_service_column,parent,false);
                holder=new ViewHolder();
                holder.columnName=convertView.findViewById(R.id.tv_column_name);
                holder.tv_line=convertView.findViewById(R.id.tv_line);
                holder.re=convertView.findViewById(R.id.re);
                convertView.setTag(holder);
            }else {
               holder= (ViewHolder) convertView.getTag();
            }
            if(bean.isSubscibe()){
                holder.columnName.setTextColor(Color.parseColor("#022222"));
                holder.re.setBackgroundColor(Color.WHITE);
                holder.tv_line.setVisibility(View.VISIBLE);
            }else {
                holder.columnName.setTextColor(Color.parseColor("#222222"));
                holder.re.setBackgroundColor(Color.parseColor("#f5f5f5"));
                holder.tv_line.setVisibility(View.GONE);
            }
            holder.columnName.setTag(position);
            holder.columnName.setText(bean.getInstitutionName());
            holder.columnName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos= (int) v.getTag();
                     GovItemBean itemBean=beans.get(pos);
                     itemBean.setSubscibe(true);
                     currentBean=itemBean;
                     getServiceDynamicList(itemBean);
                     for(GovItemBean bean1: beans){
                         if(bean1!=itemBean){
                             bean1.setSubscibe(false);
                         }
                     }

                     notifyDataSetChanged();
                }
            });
            return convertView;
        }

    }
    static class ViewHolder{
        TextView columnName,tv_line;
        RelativeLayout re;
    }
    /**
     * 获取机构新闻列表
     */
    private void getServiceDynamicList(GovItemBean bean) {

        if (TextUtils.isEmpty(bean.getInstitutionUrl())|| !bean.getInstitutionUrl().endsWith(".json")) {
            toast("数据错误");
            return;
        }

        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), bean.getInstitutionUrl(),0,new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem()) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    if(adapter==null) {
                        adapter = new NormalServiceAdapter(newsItems);
                        gridLayoutManager = new GridLayoutManager(getBaseContext(), 2);
                        canContentView.setItemAnimator(new DefaultItemAnimator());
                        canContentView.setLayoutManager(gridLayoutManager);
                        canContentView.setAdapter(adapter);
                    }else {
                        adapter.setData(newsItems);
                    }
                }else {
                    if(adapter!=null){
                        adapter.clearData();
                    }
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }


    private void getCityStateList() {
        NetUtils.getNetAdapter().getStateList(getOwnerName(), serviceUrlTemp, new AbsNetCallBack<FCityItem>(FCityItem.class) {
            @Override
            public void onSuc(FCityItem fCityItem) {
                if (fCityItem != null) {
                   cityItem=fCityItem;

                    List<GovItemBean> beans =new ArrayList<>();

                    if( ListUtils.isListValued(fCityItem.getInstitutionList())){
                        fCityItem.getInstitutionList().get(0).setSubscibe(true);
                        for(FCityState bean:fCityItem.getInstitutionList()){
                            GovItemBean gg  = new GovItemBean();
                            gg.setInstitutionName(bean.getInstitutionName());
                            gg.setInstitutionImage(bean.getInstitutionImage());
                            gg.setInstitutionId(bean.getInstitutionId());
                            gg.setInstitutionUrl(bean.getInstitutionUrl());
                            gg.setSubscibe(bean.isSubscibe());
                            beans.add(gg);

                        }

                        myadapter=new Myadapter(beans);
                        listView.setAdapter(myadapter);

                        currentBean=beans.get(0);
                        if(currentBean!=null){
                            getServiceDynamicList(currentBean);
                        }


                    }
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if(currentBean!=null){
                    getServiceDynamicList(currentBean);
                }

            }
        });
    }


    private class NormalServiceAdapter extends RecyclerView.Adapter<ServiceItemHolder>{
        private List<NewsItem> data;

        public void setData(List<NewsItem> data) {

            this.data = data;
            notifyDataSetChanged();
        }
       public void clearData(){
           if(this.data!=null){
               this.data.clear();
               notifyDataSetChanged();
           }
       }
        public NormalServiceAdapter(List<NewsItem> data) {
            this.data = data;
        }

        @Override
        public ServiceItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(getBaseContext()).inflate(R.layout.item_more_service, parent, false);
            ServiceItemHolder bah = new ServiceItemHolder(v);
            return bah;
        }

        @Override
        public void onBindViewHolder(ServiceItemHolder holder, int position) {
            final NewsItem item=data.get(position);
            holder.name.setText(item.getNewsTitle());

            holder.name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(serviceItemClick!=null){
                        serviceItemClick.OnServiceItemClick(item);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }
    public class ServiceItemHolder extends RecyclerView.ViewHolder{
        public TextView name;
        public ServiceItemHolder(View itemView) {
            super(itemView);
            name=itemView.findViewById(R.id.tv_name);
        }

    }


    private OnServiceItemClick serviceItemClick;


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private synchronized void onNetFinish() {
        if (commonRefresh.isRefreshing()) {
            commonRefresh.refreshComplete();
        }
    }


    public OnServiceItemClick getServiceItemClick() {
        return serviceItemClick;
    }

    public void setServiceItemClick(OnServiceItemClick serviceItemClick) {
        this.serviceItemClick = serviceItemClick;
    }

    public interface OnServiceItemClick{
        void OnServiceItemClick(NewsItem item);
    }
}
